package com.izhar.answeringmachine.Controller;

import com.izhar.answeringmachine.utils.ResultData;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * controller异常捕获
 * 代码超时或超出内存不再抛异常，而是直接返回特定错误码，所以 超时，超内存判定不再需要
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 捕获全局的Runtime异常
     * @param request   request
     * @param e         错误信息类
     * @return          错误信息打包类
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public ResultData BaseExceptionHandler(HttpServletRequest request,RuntimeException e){

        log.error("GlobalExceptionHandler： "+e.getMessage());

        //代码运行超时
        //if (e.getMessage().contains("time out  error")){
        //        return ResultData.getResultData("50020","runtime error","Code run time out");
        //
        ////超出内存限制
        //}else if (e.getMessage().contains("code heap space")){
        //    return ResultData.getResultData("50020","runtime error","Exceeded memory limit");
        //
        ////编译异常
        //}else if (e.getMessage().contains("compile error")){
        //    return ResultData.getResultData("50021","compile error",e.getMessage());
        //}

        //其他异常
        return ResultData.getResultData("50022","Other error", URLEncoder.encode(e.getMessage(), StandardCharsets.UTF_8));
    }
}
